/*
 * @Author: wangjing wangjin122@qq.com
 * @Date: 2024-02-23 15:09:24
 * @LastEditors: wangjing wangjin122@qq.com
 * @LastEditTime: 2024-02-23 16:40:51
 * @FilePath: \泛型\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

// 1. 动态类型
function xiaoman<T>(a: T, b: T):Array<T> {
  return [a, b]
}
xiaoman('1','2')

// 1.1 type泛型
type A<T> = string | number | T
let a:A<boolean> = 1

// 1.2 interface泛型
interface Data<T> {
  msg: T
}
let data: Data<string> = {
  msg: 'xxxx'
}

// 1.3 泛型的高级用法 可以设置默认值
function add<T, K = string>(a: T, b: K): Array<T | K> {
  return [a,b]
}
add(1, false)

// 2 泛型应用示例
const axios = {
  get<T>(url: string): Promise<T> {
    return new Promise((resolve, reject) => {
      let xhr: XMLHttpRequest = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.onreadystatechange = () => {
        if(xhr.readyState == 4 && xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
      xhr.send(null)
    })
  }
}
interface ResData {
  code: number
  msg: string
}
axios.get<ResData>('./data.json').then(res => {
  console.log(res)
})